import { Body, Controller, Get, HttpService, Post, Put, Query, Res } from '@nestjs/common';
import { Response } from 'express';
import { ApiResult, ApiResultCode } from '../../common/api-result';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PluginAliyunSetting, PluginAliyunSettingConfigKeys } from './plugin-aliyun-setting.entity';

@Controller()
export class PluginAliyunSettingController {

  constructor(
    @InjectRepository(PluginAliyunSetting)
    private aliyunSettingRepository: Repository<PluginAliyunSetting>,
  ) {
  }


  /**
   * 配置阿里云子账号 accessKey and accessSecret
   * @param dto
   * @param res
   */
  @Post('/api/plugin/aliyun-accesskey/settingIdAndSecret')
  async accessKeySettingIdAndSecret(@Body() dto: { accessKeyId: string, accessKeySecret: string }, @Res() res: Response) {
    const ar = new ApiResult();
    if (!dto.accessKeyId) {
      return res.json(ApiResultCode['2']('accessKeyId 不能为空！'));
    }
    if (!dto.accessKeySecret) {
      return res.json(ApiResultCode['2']('accessSecret 不能为空！'));
    }
    let accessKey = await this.aliyunSettingRepository.findOne({ key: PluginAliyunSettingConfigKeys.accessKeyId });
    if (!accessKey) {
      accessKey = new PluginAliyunSetting();
      accessKey.key = PluginAliyunSettingConfigKeys.accessKeyId;
    }
    accessKey.value = dto.accessKeyId;
    await this.aliyunSettingRepository.save(accessKey);

    let accessSecret = await this.aliyunSettingRepository.findOne({ key: PluginAliyunSettingConfigKeys.accessKeySecret });
    if (!accessSecret) {
      accessSecret = new PluginAliyunSetting();
      accessSecret.key = PluginAliyunSettingConfigKeys.accessKeySecret;
    }
    accessSecret.value = dto.accessKeySecret;
    await this.aliyunSettingRepository.save(accessSecret);
    return res.json(ar);
  }


}